<?php
// 上传目录
$uploadDir = __DIR__ . '/uploads/';

// 确保上传目录存在
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// 检查是否有文件上传
if (isset($_FILES['file'])) {
    $file = $_FILES['file'];
    
    // 基本错误检查
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errors = [
            UPLOAD_ERR_INI_SIZE => '上传的文件超过了php.ini中upload_max_filesize选项限制的值',
            UPLOAD_ERR_FORM_SIZE => '上传文件的大小超过了HTML表单中MAX_FILE_SIZE选项指定的值',
            UPLOAD_ERR_PARTIAL => '文件只有部分被上传',
            UPLOAD_ERR_NO_FILE => '没有文件被上传',
            UPLOAD_ERR_NO_TMP_DIR => '找不到临时文件夹',
            UPLOAD_ERR_CANT_WRITE => '文件写入失败',
            UPLOAD_ERR_EXTENSION => 'PHP扩展停止了文件上传'
        ];
        
        $errorMessage = isset($errors[$file['error']]) ? $errors[$file['error']] : '未知上传错误';
        die(json_encode(['success' => false, 'message' => $errorMessage]));
    }
    
    // 生成安全的文件名
    $fileName = basename($file['name']);
    $filePath = $uploadDir . $fileName;
    
    // 检查文件是否已存在
    $counter = 1;
    $fileInfo = pathinfo($filePath);
    while (file_exists($filePath)) {
        $fileName = $fileInfo['filename'] . "_{$counter}." . $fileInfo['extension'];
        $filePath = $uploadDir . $fileName;
        $counter++;
    }
    
    // 移动上传的文件
    if (move_uploaded_file($file['tmp_name'], $filePath)) {
        // 设置正确的文件权限
        chmod($filePath, 0644);
        
        die(json_encode(['success' => true, 'message' => '文件上传成功', 'fileName' => $fileName]));
    } else {
        die(json_encode(['success' => false, 'message' => '无法移动上传的文件']));
    }
} else {
    die(json_encode(['success' => false, 'message' => '未接收到上传的文件']));
}
?>
    